package com.hugy.test.service;

import com.mongodb.client.gridfs.model.GridFSFile;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;

@Service
@Slf4j
public class GridFsServiceImpl implements GridFsService {

    @Resource
    private GridFsTemplate gridFsTemplate;

    @Resource(name = "gridFsTestTemplate")
    private GridFsTemplate gridFsTestTemplate;

    @Override
    public String addTest() {
        File file = new File("D:\\Download\\d936.png");
        String fileName = file.getName();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("mongDb上传原图错误");
        }
        String contentType = file.getName().substring(fileName.lastIndexOf(".")+1,fileName.length());
        //            文件流：inputStream    fileName：文件的唯一标识id      file.getContentType():内容类型    metaData：元数据
//        gridFsTemplate.store(inputStream, fileName, file.getContentType(), metaData);
        ObjectId objectId = gridFsTestTemplate.store(inputStream, fileName, contentType);
        return file.getName();
    }

    @Override
    public String add() {
        File file = new File("D:\\Download\\d936.png");
        String fileName = file.getName();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("mongDb上传原图错误");
        }
        String contentType = file.getName().substring(fileName.lastIndexOf(".")+1,fileName.length());
        //            文件流：inputStream    fileName：文件的唯一标识id      file.getContentType():内容类型    metaData：元数据
//        gridFsTemplate.store(inputStream, fileName, file.getContentType(), metaData);
        ObjectId objectId = gridFsTemplate.store(inputStream, fileName, contentType);
        return file.getName();
    }

    @Override
    public void delete(String fileName) {
        gridFsTemplate.delete(new Query().addCriteria(Criteria.where("filename").is(fileName)));
    }

    @Override
    public GridFSFile select(String fileName) {
        log.info("Getting file.." + fileName);
        GridFSFile result = gridFsTemplate
                .findOne(new Query(Criteria.where("filename").is(fileName)));
        return result;
    }
}
